import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MapServerService {

  private mapObj?: google.maps.Map;
  private markerArr?: google.maps.Marker[] = [];
  private posArr?: any[] = [];
  private polygonObj?: google.maps.Polygon;

  constructor() { }

  public unbindPolygon() {
    this.polygonObj?.getMap();
  }

  public getMapObj() {
    return this.mapObj;
  }

  public setMapObj(mapObj: google.maps.Map) {
    this.mapObj = mapObj;
  }

  public addMarker(pointer: any) {
    const marker: google.maps.Marker = new google.maps.Marker({
      position: pointer,
      map: this.mapObj,
    });
    this.markerArr?.push(marker);
  }

  public getPosArr() {
    return this.posArr;
  }

  public setPosArr(type?: string) {
    if (type === 'clear') {
      this.markerArr = [];
      this.posArr = [];
    } else {
      for (var i = 0; i < 5000; i++) {
        const pos = { lat: +((Math.random() > 0.5 ? -1 : 1) * Math.random() * 84).toFixed(4), lng: +((Math.random() > 0.5 ? -1 : 1) * Math.random() * 166).toFixed(4), id: i + 1 };
        const posLatLng = new google.maps.LatLng(pos.lat, pos.lng, true);
        this.posArr?.push(pos);
        const marker: google.maps.Marker = new google.maps.Marker({
          position: posLatLng,
          map: this.mapObj,
        });
        this.markerArr?.push(marker);
      }
    }
  }

  public setCenter(pos: any) {
    this.mapObj?.setCenter(new google.maps.LatLng(pos.lat, pos.lng, true));
  }

  public getPolygon() {
    return this.polygonObj;
  }

  public createPolygon(options: google.maps.PolygonOptions) {
    this.polygonObj = new google.maps.Polygon({
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      ...options
    });
    this.mapObj && this.polygonObj.setMap(this.mapObj);
  }

  public setPolygon(option: google.maps.PolygonOptions) {
    if (this.polygonObj) {
      this.polygonObj.setOptions(option);
    } else {
      console.log('请先创建polygon对象');
    }
  }

  public removeAllMarker() {
    this.markerArr?.forEach(item => {
      item.setMap(null);
    })
    this.setPosArr('clear');
  }
}
